<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/03/23 01:49:40 $)
// $RCSfile: client_downloads.php,v $ : $Revision: 1.8 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

require_once ("./modules/downloads/functions_downloads.php");
require_once ("./modules/downloads/functions_clientdl.php");
require_once ("./includes/functions_users.php");
require_once ("./includes/functions_comments.php");
require_once ("./includes/data_mimelist.php");
$template->loadLanguageSection("downloads");

// ======= PERMISSION CHECK =======
if ($_SWIFT["user"]["permissions"]["perm_canviewdownloads"] == "0" || $_SWIFT["settings"]["dl_enableclient"] == "0")
{
	$template->assign("errormessage", $_SWIFT["language"]["perminvalid"]);
	echo $template->displayTemplate("header");
	echo $template->displayTemplate("footer");
	exit;
}

/**
* ###############################################
* VIEW CATEGORIES
* ###############################################
*/
if ($eventaction == "view")
{
	// Cache the templates before hand
	$template->cache(array('dlcatdisplay', 'dlnavbar', 'header', 'footer', 'navbar'));

	if (empty($_GET["nav"]))
	{
		$_nav = "0";
	} else {
		$_nav = htmlspecialchars($_GET["nav"]);
	}
	if ($_GET["parentcategoryid"] != 0)
	{
		$_nav .= ",".intval(htmlspecialchars($_GET["parentcategoryid"]));
	}

	// First get the parent category
	if (empty($_GET["parentcategoryid"]))
	{
		$parentcategoryid = 0;
	} else {
		$parentcategoryid = intval($_GET["parentcategoryid"]);
	}

	// Now that we have the parent category, make sure it belongs to the user group of the current user
	$_downloadcategory = checkDownloadCatUserGroup($parentcategoryid);
	if (!$_downloadcategory)
	{
		trigger_error($_SWIFT["language"]["dlcatpermerror"], E_USER_ERROR);
	}

	$template->assign("nav", $_nav);
	// Get Sub Categories
	extract(getSubCategories($parentcategoryid));

	if (count($categorylist))
	{
		$template->assign("showcategories", "1");
		$template->assign("categoryrowcount", ceil(count($categorylist)/2));
		$template->assign("splitcatlist", $splitcatlist);
		$template->assign("categorylist", $categorylist);
		$template->assign("downloaditemlist", $downloaditemlist);
	}

	$dlcatlist = array();
	$dbCore->query("SELECT downloadcategories.* FROM `". TABLE_PREFIX ."downloadcategories` AS downloadcategories LEFT JOIN `". TABLE_PREFIX ."tgroupassigns` AS tgroupassigns ON (downloadcategories.downloadcategoryid = tgroupassigns.toassignid AND tgroupassigns.type = '". TGROUP_DOWNLOADS ."') WHERE tgroupassigns.tgroupid = '". intval($_SWIFT["tgroup"]["tgroupid"]) ."' AND downloadcategories.parentcategoryid = '0' ORDER BY downloadcategories.displayorder ASC;");
	while ($dbCore->nextRecord())
	{
		if ($dbCore->Record["categorytype"] == SWIFTPUBLIC)
		{
			$dlcatlist[] = $dbCore->Record;
		}
	}

	if (count($dlcatlist))
	{
		$template->assign("incdlnav", true);
		$template->assign("dlnavcatlist", $dlcatlist);
	}

	// Ok now thats for the categories, right below the categories we also need to show any articles that might be there
	if (count($parentitemlist))
	{
		$template->assign("showitemlist", "1");
		$template->assign("parentitemlist", $parentitemlist);
	}

	// Done with the data processing, now its time to render the stuff out
	$template->assign("navigation", '<a href="index.php" id="navlink">'.$_SWIFT["language"]["navhome"].'</a> &raquo; <a href="index.php?_m=downloads&_a=view" id="navlink">'.$_SWIFT["language"]["navdownloads"]."</a>".buildDownloadNavLink($_nav));

	$template->assign("sectiontitle", $_SWIFT["language"]["dlcat"]);
	$template->assign("sectiondesc", $_SWIFT["language"]["dlcatdesc"]);
	$template->assign("pcid", intval($parentcategoryid));

	if ($parentcategoryid == 0)
	{
		$template->assign("backurl", "index.php");
	} else {
		$template->assign("backurl", "index.php?_m=downloads&_a=view&parentcategoryid=".intval($_GET["pcid"]));
	}
	echo $template->displayTemplate("dlcatdisplay");







/**
* ###############################################
* VIEW DOWNLOAD
* ###############################################
*/
} else if ($eventaction == "viewdownload") {
	$template->cache(array('dlviewdownload', 'dlitemnavbar', 'header', 'footer', 'navbar', 'comments'));

	$_downloaditem = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."downloaditems` AS downloaditems LEFT JOIN `". TABLE_PREFIX ."downloaddesc` AS downloaddesc ON (downloaditems.downloaditemid = downloaddesc.downloaditemid) WHERE downloaditems.downloaditemid = '". intval($_REQUEST["downloaditemid"]) ."';");
	if (empty($_downloaditem["downloaditemid"]))
	{
		trigger_error($_SWIFT["language"]["dlierror"], E_USER_ERROR);
	}

	renderClientComments(COMMENT_DOWNLOADS, $_downloaditem["downloaditemid"]);

	if ($_GET["invalidpass"] == 1)
	{
		$template->assign("errormessage", $_SWIFT["language"]["dliinvalidpass"]);
	}

	$_downloaditem["description"] = getProcessedHTML($_downloaditem["description"]);
	$_downloaditem["date"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $_downloaditem["dateline"]);
	$_downloaditem["lastmodified"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $_downloaditem["updatedateline"]);
	$_downloaditem["jstitle"] = addslashes($_downloaditem["title"]);

	$extension = getFileExtension($_downloaditem["filename"]);
	$mimedata = $mimelist[$extension];
	if (!empty($mimedata[1]))
	{
		$_downloaditem["icon"] = $mimedata[1];
	} else {
		$_downloaditem["icon"] = "mimeico_blank.gif";
	}
	$_downloaditem["filesize"] = formattedSize($_downloaditem["filesize"]);

	if (empty($_GET["nav"]))
	{
		$_nav = "0";
	} else {
		$_nav = $_GET["nav"];
	}
	$template->assign("docsubject", $_downloaditem["title"]);
	$template->assign("navigation", '<a href="index.php" id="navlink">'.$_SWIFT["language"]["navhome"].'</a> &raquo; <a href="index.php?_m=downloads&_a=view" id="navlink">'.$_SWIFT["language"]["navdownloads"]."</a>".buildDownloadNavLink($_nav).' &raquo; <a href="index.php?_m=downloads&_a=viewdownload&downloaditemid='. intval($_downloaditem["downloaditemid"]) .'&nav='. urlencode($_nav) .'" id="navlink">'.htmlspecialchars($_downloaditem["title"]).'</a>');

	$template->assign("downloaditem", $_downloaditem);
	$template->assign("dlitemnav", true);
	echo $template->displayTemplate("dlviewdownload");




/**
* ###############################################
* DOWNLOAD FILE
* ###############################################
*/
} else if ($eventaction == "downloadfile") {
	$_downloaditem = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."downloaditems` AS downloaditems LEFT JOIN `". TABLE_PREFIX ."downloaddesc` AS downloaddesc ON (downloaditems.downloaditemid = downloaddesc.downloaditemid) WHERE downloaditems.downloaditemid = '". intval($_REQUEST["downloaditemid"]) ."';");
	if (empty($_downloaditem["downloaditemid"]))
	{
		trigger_error($_SWIFT["language"]["dlierror"], E_USER_ERROR);
	}

	// Check for password
	if (!empty($_downloaditem["itempassword"]) && $_downloaditem["itempassword"] != md5($_REQUEST["itempassword"]))
	{
		header("location: index.php?_m=downloads&_a=viewdownload&downloaditemid=".intval($_downloaditem["downloaditemid"])."&invalidpass=1");
		exit;
	}

	// Update download count
	increaseDownloadCount($_downloaditem["downloaditemid"]);

	// Is it a link?
	if (!empty($_downloaditem["filelink"]))
	{
		header("location: ".$_downloaditem["filelink"]);
		exit;
	}

	if (!file_exists("./files/".$_downloaditem["storedfilename"]))
	{
		trigger_error($_SWIFT["language"]["dliinvalidfile"], E_USER_ERROR);
	}

	if(isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
		// IE Bug in download name workaround
		ini_set( 'zlib.output_compression','Off' );
	}

	// Get the file extension
	$extension = getFileExtension($_downloaditem["filename"]);
	if (!empty($mimelist[$extension]))
	{
		header("Content-Type: " . $mimelist[$extension] . SWIFT_CRLF);
	} else {
		header("Content-Type: application/force-download");
	}

	if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")){
		header("Content-Disposition: attachment; filename=\"". $_downloaditem["filename"] ."\"");
	} else{
		header("Content-Disposition: attachment; filename=\"". $_downloaditem["filename"] ."\"");
	}

	header("Content-Transfer-Encoding: binary");
	header("Content-Length: ". filesize("./files/".$_downloaditem["storedfilename"]));

	// Yes, just read out the file
	$fp = fopen("./files/".$_downloaditem["storedfilename"], "rb");
	if (!$fp)
	{
		return false;
	}

	while(!feof($fp)) {
		echo fread($fp, 8192);
		flush();
	}

	fclose($fp);
}


?>